package com.tim.helper.inactive.jmeter;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author Adminis
 * @date 2020年8月7日
 * DESC: 
 */
@Slf4j
public class GenJmeterThreadGroups {
	@Test
	public void genThreadGroups() throws IOException {
		String file = "WorkResponsibilityApiController.java";
		String pre = "${respApi}/";
		
		String TEST_NAME = "";
		Pattern urlPattern = Pattern.compile("^@[a-zA-Z]{3,8}Mapping");
		Pattern namePattern = Pattern.compile("^@ApiOperation");
		List<String> infos = Files.readAllLines(Paths.get("C:/Users/Adminis/Desktop/start/controller", file), StandardCharsets.UTF_8);
		for (int i = 0; i < infos.size(); i++) {
			String info = infos.get(i).trim();
			if(info.startsWith("@Api")) {
				TEST_NAME = info.substring(info.indexOf('"')+1, info.lastIndexOf('"'));
			}
			if(info.startsWith("public class")) {
				infos = infos.subList(i, infos.size());
				break;
			}
		}
		StringBuilder builder = genReq(pre, urlPattern, namePattern, infos);
		
		System.out.println(threadGroup.replace("AAAAAAAAAA", TEST_NAME).replace("BBBBBBBB", builder.toString()));
	}
	private StringBuilder genReq(String pre, Pattern urlPattern, Pattern namePattern, List<String> infos) {
		List<String> urlList = new ArrayList<>();
		List<String> nameList = new ArrayList<>();
		for (int i = 0; i < infos.size(); i++) {
			String info = infos.get(i).trim();
			if(urlPattern.matcher(info).find()) {
				int idx1 = info.indexOf("value")>0 ? info.indexOf("value")+5 : 0,
						idx2 = info.indexOf('"', idx1),	
						idx3 = info.indexOf('"', idx2+1);
				String url = info.substring(idx2+1, idx3).trim();
				url = url.startsWith("/") ? url.substring(1) : url;
				urlList.add(pre+url);
			}else if(namePattern.matcher(info).find()){
				int idx1 = info.indexOf("value")>0 ? info.indexOf("value")+5 : 0,
					idx2 = info.indexOf('"', idx1),	
					idx3 = info.indexOf('"', idx2+1);
				nameList.add(info.substring(idx2+1, idx3));
			}
		}
		if(urlList.isEmpty() || urlList.size()!=nameList.size()) {
			throw new RuntimeException("urlList is null；或者两者数量不等");
		}
		StringBuilder builder = new StringBuilder();
		for (int i = 0; i < nameList.size(); i++) {
			String name = nameList.get(i);
			String url = urlList.get(i);
			builder.append(req.replace("TEST_NAME", name).replace("REQ_PATH", url));
		}
		return builder;
	}
	@Test
	public void testMatcher() {
		Pattern pattern = Pattern.compile("^@[a-zA-Z]{3,8}Mapping");
		System.out.println(pattern.matcher(	"@GetMapping(value = \"/toList\")").find());
	}
	public static void main(String[] args) throws IOException {
		new GenJmeterThreadGroups().genThreadGroups();
	}
	
	
	String threadGroup ="\n<ThreadGroup guiclass=\"ThreadGroupGui\" testclass=\"ThreadGroup\" testname=\"AAAAAAAAAA\" enabled=\"true\">\r\n" + 
			"        <stringProp name=\"ThreadGroup.on_sample_error\">continue</stringProp>\r\n" + 
			"        <elementProp name=\"ThreadGroup.main_controller\" elementType=\"LoopController\" guiclass=\"LoopControlPanel\" testclass=\"LoopController\" testname=\"循环控制器\" enabled=\"true\">\r\n" + 
			"          <boolProp name=\"LoopController.continue_forever\">false</boolProp>\r\n" + 
			"          <stringProp name=\"LoopController.loops\">1</stringProp>\r\n" + 
			"        </elementProp>\r\n" + 
			"        <stringProp name=\"ThreadGroup.num_threads\">1</stringProp>\r\n" + 
			"        <stringProp name=\"ThreadGroup.ramp_time\">1</stringProp>\r\n" + 
			"        <boolProp name=\"ThreadGroup.scheduler\">false</boolProp>\r\n" + 
			"        <stringProp name=\"ThreadGroup.duration\"></stringProp>\r\n" + 
			"        <stringProp name=\"ThreadGroup.delay\"></stringProp>\r\n" + 
			"        <boolProp name=\"ThreadGroup.same_user_on_next_iteration\">true</boolProp>\r\n" + 
			"      </ThreadGroup>\r\n" + 
			"      <hashTree>\r\n"
			+ "BBBBBBBB\r\n"+
			"        <ResultCollector guiclass=\"ViewResultsFullVisualizer\" testclass=\"ResultCollector\" testname=\"察看结果树\" enabled=\"true\">\r\n" + 
			"          <boolProp name=\"ResultCollector.error_logging\">false</boolProp>\r\n" + 
			"          <objProp>\r\n" + 
			"            <name>saveConfig</name>\r\n" + 
			"            <value class=\"SampleSaveConfiguration\">\r\n" + 
			"              <time>true</time>\r\n" + 
			"              <latency>true</latency>\r\n" + 
			"              <timestamp>true</timestamp>\r\n" + 
			"              <success>true</success>\r\n" + 
			"              <label>true</label>\r\n" + 
			"              <code>true</code>\r\n" + 
			"              <message>true</message>\r\n" + 
			"              <threadName>true</threadName>\r\n" + 
			"              <dataType>true</dataType>\r\n" + 
			"              <encoding>false</encoding>\r\n" + 
			"              <assertions>true</assertions>\r\n" + 
			"              <subresults>true</subresults>\r\n" + 
			"              <responseData>false</responseData>\r\n" + 
			"              <samplerData>false</samplerData>\r\n" + 
			"              <xml>false</xml>\r\n" + 
			"              <fieldNames>true</fieldNames>\r\n" + 
			"              <responseHeaders>false</responseHeaders>\r\n" + 
			"              <requestHeaders>false</requestHeaders>\r\n" + 
			"              <responseDataOnError>false</responseDataOnError>\r\n" + 
			"              <saveAssertionResultsFailureMessage>true</saveAssertionResultsFailureMessage>\r\n" + 
			"              <assertionsResultsToSave>0</assertionsResultsToSave>\r\n" + 
			"              <bytes>true</bytes>\r\n" + 
			"              <sentBytes>true</sentBytes>\r\n" + 
			"              <url>true</url>\r\n" + 
			"              <threadCounts>true</threadCounts>\r\n" + 
			"              <idleTime>true</idleTime>\r\n" + 
			"              <connectTime>true</connectTime>\r\n" + 
			"            </value>\r\n" + 
			"          </objProp>\r\n" + 
			"          <stringProp name=\"filename\"></stringProp>\r\n" + 
			"        </ResultCollector>\r\n" + 
			"        <hashTree/>\r\n" + 
			"        <JSONPathAssertion guiclass=\"JSONPathAssertionGui\" testclass=\"JSONPathAssertion\" testname=\"JSON断言\" enabled=\"true\">\r\n" + 
			"          <stringProp name=\"TestPlan.comments\">path填路径，$开头，点号连接；勾选assert value；value填期望值</stringProp>\r\n" + 
			"          <stringProp name=\"JSON_PATH\">$.code</stringProp>\r\n" + 
			"          <stringProp name=\"EXPECTED_VALUE\">200</stringProp>\r\n" + 
			"          <boolProp name=\"JSONVALIDATION\">true</boolProp>\r\n" + 
			"          <boolProp name=\"EXPECT_NULL\">false</boolProp>\r\n" + 
			"          <boolProp name=\"INVERT\">false</boolProp>\r\n" + 
			"          <boolProp name=\"ISREGEX\">false</boolProp>\r\n" + 
			"        </JSONPathAssertion>\r\n" + 
			"        <hashTree/>\r\n" + 
			"      </hashTree>";
	
	String req = "        <HTTPSamplerProxy guiclass=\"HttpTestSampleGui\" testclass=\"HTTPSamplerProxy\" testname=\"TEST_NAME\" enabled=\"false\">\r\n" + 
			"          <elementProp name=\"HTTPsampler.Arguments\" elementType=\"Arguments\" guiclass=\"HTTPArgumentsPanel\" testclass=\"Arguments\" testname=\"用户定义的变量\" enabled=\"true\">\r\n" + 
			"            <collectionProp name=\"Arguments.arguments\"/>\r\n" + 
			"          </elementProp>\r\n" + 
			"          <stringProp name=\"HTTPSampler.domain\">${host}</stringProp>\r\n" + 
			"          <stringProp name=\"HTTPSampler.port\">${port}</stringProp>\r\n" + 
			"          <stringProp name=\"HTTPSampler.protocol\"></stringProp>\r\n" + 
			"          <stringProp name=\"HTTPSampler.contentEncoding\"></stringProp>\r\n" + 
			"          <stringProp name=\"HTTPSampler.path\">REQ_PATH</stringProp>\r\n" + 
			"          <stringProp name=\"HTTPSampler.method\">GET</stringProp>\r\n" + 
			"          <boolProp name=\"HTTPSampler.follow_redirects\">true</boolProp>\r\n" + 
			"          <boolProp name=\"HTTPSampler.auto_redirects\">false</boolProp>\r\n" + 
			"          <boolProp name=\"HTTPSampler.use_keepalive\">true</boolProp>\r\n" + 
			"          <boolProp name=\"HTTPSampler.DO_MULTIPART_POST\">false</boolProp>\r\n" + 
			"          <stringProp name=\"HTTPSampler.embedded_url_re\"></stringProp>\r\n" + 
			"          <stringProp name=\"HTTPSampler.connect_timeout\"></stringProp>\r\n" + 
			"          <stringProp name=\"HTTPSampler.response_timeout\"></stringProp>\r\n" + 
			"        </HTTPSamplerProxy>\n"+ 
			"        <hashTree/>\r\n";
}
